package com.tjvib.view.activity;

import static com.tjvib.Constants.SUCCESS;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.tjvib.R;
import com.tjvib.base.BaseActivity;
import com.tjvib.presenter.BasePresenter;
import com.tjvib.util.LogUtil;
import com.tjvib.util.Manager.AppManager;
import com.tjvib.util.Manager.UserManager;
import com.tjvib.util.SharedPreferencesUtil;
import com.tjvib.util.ToastUtil;
import com.tjvib.util.retrofit.BaseResponse;
import com.tjvib.util.retrofit.RetrofitHelper;
import com.tjvib.view.dialog.LoadingDialog;
import com.tjvib.widget.AndroidScheduler;
import com.tjvib.widget.ItemGroup;

import org.json.JSONObject;

import java.util.HashMap;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class PwdActivity extends BaseActivity {

    private ImageView pwd_iv_icon;
    private EditText pwd_et_con;
    private Button pwd_btn_upload;
    private ItemGroup pwd_ig_phone, pwd_ig_name;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_pwd;
    }

    @Override
    protected boolean initView() {
        pwd_iv_icon = findViewById(R.id.pwd_iv_icon);
        pwd_et_con = findViewById(R.id.pwd_et_con);
        pwd_iv_icon.setOnClickListener(v-> startActivity(new Intent(this, IconActivity.class)));

        pwd_btn_upload = findViewById(R.id.pwd_btn_upload);
        pwd_btn_upload.setOnClickListener(v-> {
            String pwd = pwd_et_con.getText().toString();
            String name = pwd_ig_name.getContentEdit().getText().toString();
            if(pwd.isEmpty())
                ToastUtil.show("新密码不能为空");
            else if(name.isEmpty())
                ToastUtil.show("用户名不能为空");
            else
                setPwd(pwd, name);
        });

        pwd_ig_phone = findViewById(R.id.pwd_ig_phone);
        pwd_ig_name = findViewById(R.id.pwd_ig_name);
        return true;
    }

    @Override
    protected boolean initData() {
        Glide.with(this).load(UserManager.getInstance().getImage()).into(pwd_iv_icon);
        pwd_ig_phone.setItem_group_et_con(UserManager.getInstance().getPhoneNumber());
        pwd_ig_name.setItem_group_et_con(UserManager.getInstance().getUsername());
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        LoadingDialog loadingDialog = new LoadingDialog(PwdActivity.this);
        loadingDialog.showDialog(PwdActivity.this, "正在更新用户信息…");
        RetrofitHelper.getInstance().create().get_info(String.valueOf(UserManager.getInstance().getUserId()))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidScheduler.mainThread())
                .subscribe(new Observer<BaseResponse>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseResponse value) {
                        loadingDialog.dismiss();
                        if (value.getCode() == SUCCESS) {
                            LogUtil.d(value.getMessage() + "\n" + value.getData());
                            String token = UserManager.getInstance().setInfo(String.valueOf(value.getData()));
                            if (!token.isEmpty())
                                SharedPreferencesUtil.saveToken(PwdActivity.this, token);
                            Glide.with(PwdActivity.this).load(UserManager.getInstance().getImage()).into(pwd_iv_icon);
                        } else {
                            LogUtil.e(value.getCode() + "\n" + value.getMessage() + "\n" + value.getData());
                            showErrorDialog(value.getMessage());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        loadingDialog.dismiss();
                        LogUtil.e("get_info" + e.getMessage());
                        showErrorDialogAndExit(e.getMessage() + "\n请重新登录");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    protected BasePresenter genPresenter() {
        return null;
    }

    private void setPwd(String pwd, String name){
        LoadingDialog loadingDialog = new LoadingDialog(this);
        loadingDialog.showDialog(this, "提交修改中...");
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"),
                getUserInfo(pwd, name));
        RetrofitHelper.getInstance().create()
                .change_info(requestBody, String.valueOf(UserManager.getInstance().getUserId()))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidScheduler.mainThread())
                .subscribe(new Observer<BaseResponse>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseResponse value) {
                        LogUtil.i(value.getCode()+" "+value.getMessage()+" "+value.getData());
                        loadingDialog.dismiss();
                        if (value.getCode() == SUCCESS) {
                            ToastUtil.show("设置成功");
                            AppManager.getInstance().finishOtherActivity(MainActivity.class);
                            startActivity(new Intent(PwdActivity.this, MainActivity.class));
                        } else
                            showErrorDialog(value.getMessage());
                    }

                    @Override
                    public void onError(Throwable e) {
                        loadingDialog.dismiss();
                        showErrorDialog(e.getMessage());
                        LogUtil.e(e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private String getUserInfo(String pwd, String name){
        HashMap<String, Object> map = new HashMap<>();
        map.put("analysisTrial", UserManager.getInstance().getAnalysisTrial());
        map.put("balance", UserManager.getInstance().getBalance());
        map.put("collectLocalTrial", UserManager.getInstance().getCollectLocalTrial());
        map.put("collectLpmsTrial", UserManager.getInstance().getCollectLpmsTrial());
        map.put("enabled", UserManager.getInstance().isEnabled());
        map.put("id", UserManager.getInstance().getUserId());
        map.put("image", UserManager.getInstance().getImage());
        map.put("password", pwd);
        map.put("phoneNumber", UserManager.getInstance().getPhoneNumber());
        map.put("userName", name);
        map.put("vip", UserManager.getInstance().isVip());

        LogUtil.e("getUserInfo: map json:" + new JSONObject(map).toString());
        return new JSONObject(map).toString();
    }
}